﻿// Contact management application w/Firbase v1.2
// - refactoring
// - full CRUD on contacts
// - GET, POST, DELETE, PUT

var myContacts = (function () {

    var contactsObj = [];       // array of all contacts
    var contactsShuffled = []   // array of randomized contacts

    var contactToUpdate;        // contain the index Id of the current contact
    var baseUrl = "315demo";    // unique Firebase app name

    /* Helper methods ------------------------------------------------------------*/
    // Generates final url for Firebase calls.
    function urlMaker() {
        var url = "Https://" + baseUrl + ".firebaseio.com/contacts/"
        for (var i = 0; i < arguments.length; i++) {
            url += arguments[i] + "/";
        }
        url += ".json";
        console.log("final url:", url);
        return url;
    }
    // handle all XHR calls
    // @ verb - Http method 
    // @ url - firebase app url (Fetch & Post to)
    // @ data - the object to send to FB
    // @ callback_success - method to call on Success
    // @ callback_error - method to call on Error
    // @ extra - future need
    function masterXhr(verb, url, data, callback_success, callback_error, extra) {
        console.log(verb, url, data);
        var request = new XMLHttpRequest();
        request.open(verb, url, true);
        request.onload = function () {
            if (this.status >= 200 && this.status < 400) {
                if (callback_success && typeof (callback_success) == "function") {
                    callback_success(JSON.parse(this.response));
                }
            } else {
                if (callback_error && typeof (callback_error) == "function") {
                    callback_error("MASTER XHR ERROR: " + this.response);
                }
            }
        };
        if (data) {  // check on VERB type (GET or POST)
            request.send(JSON.stringify(data))
        } else {
            request.send();
        }
    }


    /* Contacts Constructor --------------------------------------------------------------------------- */
    function Contact(fName, lName, phone, email, guid) {
        this.fname = fName,
        this.lname = lName,
        this.phone = phone,
        this.email = email,
        this.id = guid
    }

    /* GET --------------------------------------------------------------------------- */
    // PRIVATE - Get contacts from Firebase
    function getFirebaseContacts() {
        masterXhr('GET', urlMaker(), null, showFbContent, genericErrorCallback);
    };

    // render FB content to screen
    function showFbContent(tData) {
        contactsObj = [];           // clear the object
        var counter = 0;
        var contactObj; // contact object from the constructor
        for (var i in tData) {
            var contact = tData[i];
            // creating a new Contact object
            contactObj = new Contact(contact.fname, contact.lname, contact.phone, contact.email, i);
            // add it (newly created Contacts object) to the array
            contactsObj.push(contactObj);
            // render to screen
            renderContactsToScreen();
        }
    }
    // only render the Contacts array
    function renderContactsToScreen() {

        var tCnt;                   // temp Contact 
        var tStr = "";              // temp string used for concat
        var tRes = $("#tableResults");   // element to render content
        tRes.empty();               // clear the html
        var headerString = '<tr><td>ID</td><td>Name</td><td>Email</td><td>Phone</td><td>Actions</td></tr>';
        tRes.append(headerString);
        var counter = 0;
        var contactObj;                // contact object from the constructor
        for (var i in contactsObj) {
            var contact = contactsObj[i];

            // Action buttons
            var editBtn = '<button  onclick="myContacts.doEdit(' + counter + ')" type="button" class="btn btn-warning btn-xs"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button>'
            var deleteBtn = '<button onclick="myContacts.doDelete(' + counter + ')" type="button" class="btn btn-danger btn-xs"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>'

            // render to screen
            tStr = "";              // clear the temp string
            tStr += "<tr>";
            tStr += "<td>" + counter + "</td>";
            tStr += "<td>" + contact.fname + " " + contact.lname + "</td>";
            tStr += "<td>" + contact.email + "</td>";
            tStr += "<td>" + contact.phone + "</td>";
            tStr += "<td>" + editBtn + " " + deleteBtn + "</td>"
            tStr += "</tr>"
            counter++;
            tRes.append(tStr);
        }
    }


    /* ADD --------------------------------------------------------------------------- */
    // Adds a contact to FireBase via AJAX
    function addBuilder() {
        addFirebaseContact(mySuccess, myErr)
    }
    function addFirebaseContact(successCallback, errorCallback) {
        var fName = $("#cFname").val();
        var lName = $("#cLname").val();
        var userName = fName + lName;
        var tPhone = $("#cPhone").val();
        var tEmail = $("#cEmail").val();
        console.log(fName, lName, tPhone, tEmail);
        var objToPost = {
            "fname": fName,
            "lname": lName,
            "email": tEmail,
            "phone": tPhone,
            "userName": userName

        }
        /*
{"joesmith": {
"fname": "Joey",
"lname": "Smithers",
"email": "ok@ok.com",
"phone": "5555555"
}
}
*/
        // AJAX call for POST
        masterXhr('POST', urlMaker(), objToPost, function (msg) {
            objToPost.id = msg.name;
            contactsObj.push(objToPost);
            console.log(msg.name, objToPost)
            renderContactsToScreen();
        }, errorCallback);


    }



    /* DELETE --------------------------------------------------------------------------- */
    // xhr for deleting a contact
    function deleteBuilder(id) {
        console.log("hit deleteBuilder");
        goFirebaseDelete(id, mySuccess, myErr)
    }
    function goFirebaseDelete(cId, cbSuccess, cbError) {
        masterXhr('DELETE', urlMaker(contactsObj[cId].id), null, function () {
            contactsObj.splice(cId, 1);
            renderContactsToScreen();
        }, genericErrorCallback);
    }
    //
    function peanutButtter() {
        console.log("hit my Peanutbutter Success callback");
        getFirebaseContacts();
    }
    // callback - get the latest from FB
    function mySuccess() {
        console.log("hit my Success callback");
        getFirebaseContacts();
    }
    // calback - generic error message
    function myErr() {
        console.log("hit my Err callback");
    }


    /* UPDATE --------------------------------------------------------------------------- */
    // populate & show the modal
    function showEditDialog(tempId) {
        // save the ID to local variable

        //contactToUpdate = contactsObj[tempId].id;
        contactToUpdate = tempId;

        // create temp object of Contact in array (based on index argument)
        var tContact = contactsObj[tempId];
        //populate the fields
        $('#uFname').val(tContact.fname);
        $('#uLname').val(tContact.lname);
        $('#uPhone').val(tContact.phone);
        $('#uEmail').val(tContact.email);
        $('#myEditModal').modal("show");
        //
        console.log("THE CONTACT TO UPDATE:", tContact);
        console.log("THE ID for the contact to update:", contactToUpdate);

    }

    // save the contents of the modal
    function updateFirebaseContact() {
        var name = $('#uFname').val();
        var last = $('#uLname').val();
        var phone = $('#uPhone').val();
        var email = $('#uEmail').val();
        console.log(name, last, phone, email);
        // create obj from vars
        var objToPost = {
            "fname": name,
            "lname": last,
            "email": email,
            "phone": phone
        }
        // get the guid
        var cGuid = contactsObj[contactToUpdate].id
        // ajax call to save
        masterXhr('PATCH', urlMaker(contactsObj[contactToUpdate].id), objToPost, function () {
            //
            console.log(this.response);
            contactsObj[contactToUpdate] = objToPost;
            renderContactsToScreen(); // refresh the view
            //
        }, genericErrorCallback)

    }


    // 
    function genericErrorCallback(msg) {
        alert(msg)
    }


    /// load data onload..
    getFirebaseContacts();


    //function to clear the results
    var clearResults = function () {
        $("#results").empty();
    }

    /* RANDOMIZER ---------------------------------- */
    function randomizer(arr) {
        for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i),
            x = arr[--i], arr[i] = arr[j], arr[j] = x);
        return arr;
    }

    function doRandomizer() {
        var mixedArray = randomizer(contactsObj);
        console.log(mixedArray);

        var pairedStudents = []; // paired list of students
        var tempCounter = 0;
        var fixedlen = mixedArray.length

        for (var i = 0; i < fixedlen; i++) {
            if (mixedArray.length == 0) {
                break;
            }
            var temp2 = mixedArray.splice(0, 2);
            //console.log(mixedArray.length, i, temp2);
            pairedStudents.push(temp2);

            var longStr = "Team #" + (i + 1) + " " + temp2[0].fname + " & " + temp2[1].fname;
            console.log(longStr);

        }
    }



    // expose public methods
    return {
        doAdd: addBuilder,
        doEdit: showEditDialog,
        doDelete: deleteBuilder,
        doAjax: getFirebaseContacts,
        doSave: updateFirebaseContact,

        doRandomizer: doRandomizer

    }

    /* POLLING ----------------------------------------------------*/


})();
